package com.shz.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shz.pojo.Blog;
import com.shz.pojo.BlogImgs;
import com.shz.pojo.User;
import com.shz.service.*;
import com.shz.utils.DateUtils;
import com.shz.utils.GeoDistanceCalculator;
import com.shz.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shz
 * @since 2024-09-02
 */
@Api(tags = "博客模块")
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Resource
    BlogService blogService;
    @Resource
    BlogImgsService blogImgsService;
    @ApiOperation(value = "创建博客")
    @PostMapping("/save")
    public  boolean save(@RequestBody Blog blog){
        blog.setLiked(0);
        blog.setMark(0);
        blog.setSee(false);
        blog.setStatus(false);
        blog.setCreatetime(DateUtils.getNowDate());

        Integer id = UserUtil.getCurrentUser().getId();
        blog.setUsername(UserUtil.getCurrentUser().getUsername());
        blog.setUid(id);
        blogService.save(blog);
        for (String url : blog.getUrls()) {
            BlogImgs b=new BlogImgs();
            b.setUrl(url);
            b.setBid(blog.getId());
            blogImgsService.save(b);
        }
        return true;
    }
    @ApiOperation(value = "修改博客")
    @PutMapping("/update")
    public boolean update(@RequestBody Blog blog){
        blog.setLiked(0);
        blog.setMark(0);
        blog.setSee(false);
        blog.setStatus(false);
        blog.setCreatetime(DateUtils.getNowDate());
        Integer id = UserUtil.getCurrentUser().getId();
        blog.setUid(id);
        blogImgsService.remove(new QueryWrapper<BlogImgs>().eq("bid",blog.getId()));
        for (String url : blog.getUrls()) {
            BlogImgs b=new BlogImgs();
            b.setUrl(url);
            b.setBid(blog.getId());
            blogImgsService.save(b);
        }
        return blogService.updateById(blog);

    }
    @ApiOperation(value = "博客详情")
    @ApiImplicitParam(name = "id", value = "博客id", required = true)
    @GetMapping("/getDetailById/{id}")
    public  Blog getDetailById(@PathVariable("id") Integer id){
        Blog b = blogService.query().eq("id", id).one();
        Long count = userLikeService.query().eq("bid", b.getId()).count();
        Long count2 = userMarkService.query().eq("bid", b.getId()).count();
        b.setLiked(Math.toIntExact(count));
        b.setMark(Math.toIntExact(count2));
        List<BlogImgs> blogImgsList = blogImgsService.query().eq("bid", b.getId()).list();
        List<String> urls = blogImgsList.stream().map(BlogImgs::getUrl).collect(Collectors.toList());
        b.setUrls(urls);
        return b;
    }
    @Resource
    UserLikeService userLikeService;
    @Resource
    UserMarkService userMarkService;
    @ApiOperation(value = "我的博客列表,status=0且see=1未通过审核博客，status=1,为通过审核博客，status=0且see=0,博客审核中")
    @GetMapping("/getMyBlogs")
    public List<Blog> getMyBlogs(){
        List<Blog> res = blogService.query().eq("uid", UserUtil.getCurrentUser().getId()).list();
        for (Blog re : res) {
            List<BlogImgs> list = blogImgsService.query().eq("bid", re.getId()).list();
            List<String> urls=list.stream().map(BlogImgs::getUrl).collect(Collectors.toList());
            Long count = userLikeService.query().eq("bid", re.getId()).count();
            Long count2 = userMarkService.query().eq("bid", re.getId()).count();
            re.setLiked(Math.toIntExact(count));
            re.setMark(Math.toIntExact(count2));
            re.setUrls(urls);

        }
        return res;
    }



    @Resource
    UserService userService;
    @ApiOperation(value = "我的关注博客列表")
    @GetMapping("/getBlogsByFollow")
    public List<Blog> getBlogsByFollow(){
        Integer id = UserUtil.getCurrentUser().getId();
        List<User> li = userService.query().eq("uid", id).list();
        List<Integer> ids = li.stream().map(User::getId).collect(Collectors.toList());
        List<Blog> res = blogService.query().in("uid", ids).eq("status", true).orderByDesc("createTime").list();
        for (Blog re : res) {
            List<BlogImgs> list = blogImgsService.query().eq("bid", re.getId()).list();
            List<String> urls=list.stream().map(BlogImgs::getUrl).collect(Collectors.toList());
            re.setUrls(urls);
            Long count = userLikeService.query().eq("bid", re.getId()).count();
            Long count2 = userMarkService.query().eq("bid", re.getId()).count();
            re.setLiked(Math.toIntExact(count));
            re.setMark(Math.toIntExact(count2));
        }
        return res;
    }
    @ApiOperation(value = "离我的距离从近到远博客列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "x", value = "我所在位置的经度坐标", required = true),
            @ApiImplicitParam(name = "y", value = "我所在位置的纬度坐标", required = true),
    })
    @GetMapping("getBlogsByDistance/{x}/{y}")
    public List<Blog> getBlogsByDistance(@PathVariable("x") Double x,@PathVariable("y")Double y){
        List<Blog> res = blogService.query().eq("status", true).list();
        for (Blog re : res) {
            List<BlogImgs> list = blogImgsService.query().eq("bid", re.getId()).list();
            List<String> urls=list.stream().map(BlogImgs::getUrl).collect(Collectors.toList());
            re.setUrls(urls);
            Long count = userLikeService.query().eq("bid", re.getId()).count();
            Long count2 = userMarkService.query().eq("bid", re.getId()).count();
            re.setLiked(Math.toIntExact(count));
            re.setMark(Math.toIntExact(count2));
        }
        // 先按距离排序
        Collections.sort(res, Comparator.comparingDouble(o ->
                GeoDistanceCalculator.calculateDistance(y, x, o.getY(), o.getX())
        ));

        // 对于相同距离的博客按 createTime 时间倒序排列
        Collections.sort(res, Comparator.comparing(Blog::getCreatetime).thenComparingDouble(o ->
                GeoDistanceCalculator.calculateDistance(y, x, o.getY(), o.getX())
        ).reversed());
        return res;

    }
    @ApiOperation(value = "根据时间返回所有笔记")
    @GetMapping("/getAllBlogByTime")
    public List<Blog> getAllBlogByTime(){
        List<Blog> res = blogService.query().eq("status", true).orderByDesc("createTime").list();
        for (Blog re : res) {
            List<BlogImgs> list = blogImgsService.query().eq("bid", re.getId()).list();
            List<String> urls=list.stream().map(BlogImgs::getUrl).collect(Collectors.toList());
            re.setUrls(urls);
            Long count = userLikeService.query().eq("bid", re.getId()).count();
            Long count2 = userMarkService.query().eq("bid", re.getId()).count();
            re.setLiked(Math.toIntExact(count));
            re.setMark(Math.toIntExact(count2));
        }
        return res;
    }

}

